/* eslint-disable no-plusplus */
/**
 * 将数据组装成csv文件下载
 * @param rows csv每行的数据，字符串二维数组
 * @param header csv文件的头，字符串数组
 * @param filename csv下载后的文件名，例如test.csv
 */
export function downloadCsv(rows, header, filename) {
  console.warn('downloadCsv has potential security risk, please replace it to downloadXlsx');
  // eslint-disable-next-line func-names
  const processRow = function(row) {
    let finalVal = '';
    for (let j = 0; j < row.length; j++) {
      let innerValue = typeof row[j] === 'undefined' || row[j] === null ? '' : row[j].toString();
      if (row[j] instanceof Date) {
        innerValue = row[j].toLocaleString();
      }
      let result = innerValue.replace(/"/g, '""');
      if (result.search(/("|,|\n)/g) >= 0) {
        result = `"${result}"`;
      }
      if (j > 0) {
        finalVal += ',';
      }
      finalVal += result;
    }
    return `${finalVal}\n`;
  };

  let csvFile = '';
  const Navigator = navigator;
  const csvarray = [`${header.join(',')}\n`];
  const { userAgent } = Navigator;
  // eslint-disable-next-line @typescript-eslint/prefer-for-of
  for (let i = 0; i < rows.length; i++) {
    csvarray.push(processRow(rows[i]));
  }
  csvFile += csvarray.join('');
  // 处理中文乱码
  if (csvFile.charAt(0) !== '\uFEFF') {
    csvFile = `\uFEFF${csvFile}`;
  }

  const blob = new Blob([csvFile], {
    type: 'text/csv;charset=utf-8;',
  });
  if (Navigator.msSaveBlob) {
    Navigator.msSaveBlob(blob, filename);
  } else if (
    userAgent.indexOf('MSIE 9.0') > 0 ||
    (userAgent.indexOf('Safari') > 0 && userAgent.indexOf('Chrome') < 0)
  ) {
    console.log('--err--', '该浏览器暂不支持导出功能,请用谷歌浏览器试下');
  } else {
    const link = document.createElement('a');
    // if (!link.download) {
    const url = URL.createObjectURL(blob);
    link.setAttribute('href', url);
    link.setAttribute('download', filename);
    link.style.visibility = 'hidden';
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    //  }
  }
}
